package com.kd.juhaowan.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.kd.juhaowan.base.BoxCacheManager;
import com.kd.juhaowan.http.api.exception.TokenException;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.ui.LoginAccountActivity;
import com.kd.juhaowan.utils.LogUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class SmartFreshBaseFragment extends Fragment implements OnRefreshListener, OnLoadMoreListener, OnHttpListener {
    private int mCurrentPageCount = 0;
    private boolean isRefresh;

    private View mRootView;

    private boolean isReCreateView;
    private Unbinder mUnbinder;
    BoxCacheManager manager;
    private ActivityResultLauncher<Intent> baseFragmentRegister;
    protected abstract void reInitDate();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        this.isReCreateView = mRootView != null;
        if (mRootView == null) {
            mRootView = doInflateContentView(inflater, container, getViewLayoutResourceId());
        }

        if (isSavedInstanceState()) {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }

        mUnbinder = ButterKnife.bind(this, mRootView);
        baseFragmentRegister = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                LogUtil.debugLog( "onActivityResult: _____" + result);
                if (result != null) {

                    if (result.getResultCode() == Activity.RESULT_OK) {
                        reInitDate();

                    }
                }
            }
        });
        if(!isReCreateView){
            manager = BoxCacheManager.getInstence(getContext());
            onButterKnifeCreateViewAfter();
            getSmartRefreshLayout().setEnableLoadMore(true);
            getSmartRefreshLayout().setOnRefreshListener(this);
            getSmartRefreshLayout().setOnLoadMoreListener(this);
        }
        return mRootView;
    }
    protected boolean isSavedInstanceState() {
        return false;
    }
    protected abstract int getViewLayoutResourceId();
    protected void onButterKnifeCreateViewAfter() {
    }
    protected View doInflateContentView(LayoutInflater inflater, ViewGroup root, int resource) {
        if (inflater == null) {
            if (!isNullContext()) {
                inflater = LayoutInflater.from(getActivity());
            } else {
                return null;
            }
        }
        return inflater.inflate(resource, root, false);
    }

    protected boolean isNullContext() {
        return getActivity() == null;
    }

    @Override
    public void onHttpSuccess(Object result) {
        mCurrentPageCount = isRefresh ? 1 : mCurrentPageCount + 1;
        LogUtil.debugLog("base smartFragment success"+mCurrentPageCount);

        finishRefreshOrLoadMore(true, false);
        LogUtil.debugLog("base Fragment success");
    }




    protected abstract SmartRefreshLayout getSmartRefreshLayout();

    protected abstract String getSmartRefreshTaskTag();

    protected abstract void onRequestNextPageData(int page);

    protected abstract boolean isNullData(HttpData response);



    @Override
    public void onHttpSuccess(Object result, boolean cache) {
//        super.onHttpSuccess(result, cache);
//            mCurrentPageCount = isRefresh ? 1 : mCurrentPageCount + 1;
        LogUtil.debugLog("base smartFragment success"+mCurrentPageCount);

        finishRefreshOrLoadMore(true, false);
    }

    @Override
    public void onHttpFail(Exception e) {
        LogUtil.debugLog("base faild"+e.getMessage());
        if(e instanceof TokenException){
            manager.writeAutoLogin(false);
            startActivity(new Intent(getActivity(), LoginAccountActivity.class));
//            getActivity().finish();
        }else {
            ToastUtils.show(e.getMessage());

            LogUtil.debugLog("base faild"+e.getMessage());

        }
    }



    public void finishRefreshOrLoadMore(boolean success, boolean noMoreData) {
        if (getSmartRefreshLayout() != null) {
            if (isRefresh) {
                getSmartRefreshLayout().finishRefresh(DEFAULT_DELAYED_SECOND, success, noMoreData);
            } else {
                getSmartRefreshLayout().finishLoadMore(DEFAULT_DELAYED_SECOND, success, noMoreData);
            }
        }
    }
    private static final int DEFAULT_DELAYED_SECOND = 0;
    @Override
    public void onLoadMore(RefreshLayout refreshLayout) {
        this.isRefresh = false;
        onRequestNextPageData(mCurrentPageCount + 1);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        this.isRefresh = true;
        onRequestNextPageData(1);
    }
}
